use crate::utils::software_checker::software_checker_creater;
use crate::{types::structs::Table, utils::get_sys_info::SysInfo};
use html_builder::{self, Buffer, Html5};
use std::fmt::Write;
use std::fs::File;
use time::format_description;

pub fn run(table_data: Table, file_path: Option<String>, sys_info: Option<SysInfo>) {
    let mut buf = Buffer::new();
    buf.doctype();
    let mut html = buf.html().attr("lang='zh-cn'");
    let mut binding = html.head();
    binding.meta().attr("charset='utf-8'");
    let mut style = binding.style();
    writeln!(style, "{}", include_str!("./assets/styles/table.css")).unwrap();
    let mut body_binding = html.body();
    match sys_info {
        Some(sys_info) => {
            writeln!(body_binding.h1(), "{}", "系统信息").unwrap();
            let mut table = body_binding.table();
            let mut thead = table.thead();
            let mut thead_tr = thead.tr();
            let table_head = vec!["计算机名称", "cpu频率", "内存大小"];
            for cell in table_head {
                writeln!(thead_tr.th(), "{}", cell).unwrap();
            }
            let mut tbody = table.tbody();
            let mut tr = tbody.tr();
            for cell in vec![sys_info.hostname, sys_info.cpu_speed, sys_info.mem_total] {
                writeln!(tr.td(), "{}", cell).unwrap();
            }
        }
        None => {}
    }
    let format =
        format_description::parse("[year]年[month]月[day]日 [hour]:[minute]:[second]").unwrap();
    let now = time::OffsetDateTime::now_local().unwrap();
    writeln!(
        body_binding.h1(),
        "{}-扫描日期:{}",
        "软件清单",
        now.format(&format).unwrap()
    )
    .unwrap();
    let mut table = body_binding.table();
    let mut binding = table.thead();
    let mut tr = binding.tr();
    for cell in table_data.head {
        writeln!(tr.th(), "{}", cell).unwrap();
    }
    let mut binding = table.tbody();
    let software_unuseable = software_checker_creater();
    for line in table_data.body {
        let mut tr = binding.tr();
        if software_unuseable(line.clone()) {
            tr = tr.attr("class='warn'");
        }
        for cell in line {
            writeln!(tr.td(), "{}", cell).unwrap()
        }
    }
    let str = buf.finish();
    let path = match file_path {
        Some(path) => path,
        None => "a.html".to_owned(),
    };
    let mut file = File::create(path).unwrap();
    std::io::Write::write(&mut file, str.as_bytes()).unwrap();
}
